package cn.sciento.farm.devicemanager.dao.config;

import cn.sciento.farm.devicemanager.common.util.BaseContextHandler;
import io.grpc.*;
import org.apache.commons.lang3.StringUtils;

public class TenantInterceptor implements ServerInterceptor {

    private String tenantName = "tenant";

    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
        Metadata.Key<String> tenantKey= Metadata.Key.of(tenantName, Metadata.ASCII_STRING_MARSHALLER);
        String tenantId= headers.get(tenantKey);
        if(StringUtils.isEmpty(tenantId)) {
            call.close(Status.INVALID_ARGUMENT, headers);
        }
        System.out.println("获取tenant");
            BaseContextHandler.setTenantId(tenantId);
            return next.startCall(new ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT>(call) {
                @Override
                public void close(Status status, Metadata trailers) {
                    super.close(status, trailers);
                    BaseContextHandler.remove();
                    System.out.println("清除-----");
                }
            }, headers);

    }
}
